/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.gr.jcash.util.converter;

import br.com.gr.jcash.ctr.CategoriaController;
import br.com.gr.jcash.dmp.Categoria;
import br.com.gr.jcash.exception.JCashException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author gelson
 */
@FacesConverter(forClass = Categoria.class)
public class CategoriaConverter implements Converter {

    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            return null;
        }
        CategoriaController controller = (CategoriaController) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, "categoriaController");
        try {
            return controller.bo.buscarPorId(getKey(value));
        } catch (JCashException ex) {
            return null;
        }
    }

    Long getKey(String value) {
        Long key;
        key = Long.valueOf(value);
        return key;
    }

    String getStringKey(Long value) {
        StringBuffer sb = new StringBuffer();
        sb.append(value);
        return sb.toString();
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Categoria) {
            Categoria o = (Categoria) object;
            return getStringKey(o.getIdCat());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Categoria.class.getName());
        }
    }
}